export default function (func) {
	function optionsFormat(func) {
		let options = func || {}
		if (typeof func === "function") {
			options = func.call(this)
		}
		// #ifdef MP-JD
		options.path = options.path.replace(/^\//, "")
		// #endif

		return options
	}
	return {
		data() {
			return {
				loginMixinData: {
					authResult: "",
					code: "",
				},
			}
		},

		async onShow() {
			// #ifndef H5
			// await this.getLoginCode()
			// #endif

			// #ifdef H5
			const options = optionsFormat.call(this, func)

			const code = window.location.href.match(/(\?|\&)code=([^&]*)/)?.[2]
			const token = uni.getStorageSync("token")
			if (!token) {
				if (/MicroMessenger/i.test(window.navigator.userAgent)) {
					window.location = options.url
				}
			} else {
				if (code) {
					uni.getStorageSync("login-code", code)
					this.loginMixinData.code = code
				}
			}
			// #endif
		},

		methods: {
			getLoginCode() {
				// #ifdef MP || APP-PLUS
				const options = optionsFormat.call(this, func)

				const toLogin = (resolve, reject) => {
					uni.login({
						provider: options.provider || options.type || "weixin",
						// #ifdef MP-ALIPAY
						scopes: options.scopes || "auth_base", // auth_base (静默授权) / auth_user (主动授权) / auth_zhima (芝麻信用)
						// #endif
						success: ({ authResult, code }) => {
							this.loginMixinData.authResult = authResult
							this.loginMixinData.code = code
							resolve({ code, authResult })
						},
						fail: reject,
					})
				}

				return new Promise((resolve, reject) => {
					if (this.loginMixinData.code) {
						uni.checkSession({
							success: () => {
								resolve({
									code: this.loginMixinData.code,
									authResult: this.loginMixinData.authResult,
								})
							},
							fail: () => {
								toLogin(resolve, reject)
							},
						})
					} else {
						toLogin(resolve, reject)
					}
				})
				// #endif

				// #ifdef H5
				return Promise.resolve({
					code: uni.getStorageSync("login-code"),
				})
				// #endif
			},
		},
	}
}
